package com.guardian;

import com.guardian.command.CommandManager;
import com.guardian.exception.InitializationException;
import com.guardian.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 启动参数
 * @author: huwei
 * @date: 2019/10/11 9:39
 * @version: 1.0.0
 */
public class StartupArgument {
    public static final String COMMAND_PORT = "-p";
    /**
     * 参数前缀
     */
    private static final String ARGUMENT_PREFIX = "-";

    /**
     * 默认端口
     */
    private static final int DEFAULT_PORT = 9766;

    private static int port = DEFAULT_PORT;

    /**
     * 原始参数
     */
    private static String[] originalArgument;

    /**
     * 参数的map映射
     */
    private static Map<String ,String[]> argumentMap;

    public static void initStartupArgument(String[] args) throws InitializationException {
        originalArgument = args;
        argumentMap = parseArgument();
    }

    /**
     * 原始参数解析
     * @return 返回参数的map映射
     */
    public static Map<String ,String[]> argumentMap() {
        return argumentMap;
    }

    public static String[] getArgument(String argumentName){
        return argumentMap().get(argumentName);
    }

    public static boolean containsArgument(String argumentName){
        return argumentMap().containsKey(argumentName);
    }

    /**
     * 原始参数string表现形式
     * @return
     */
    public static String originalArgument(){
       return StringUtil.arrayToString(originalArgument ," ");
    }

    /**
     * 解析启动参数
     * 启动参数传入规则：
     * 命令标识 + 空格 + 命令参数
     * 示例：
     * -p 8869
     * @return
     * @throws InitializationException
     */
    private static Map<String,String[]> parseArgument() throws InitializationException {
        Map<String,String[]> map = new HashMap<>(16);

        String[] temp = originalArgument;
        for(int i = 0 ,len = temp.length ;i < len ;++i){
            String argI = temp[i];
            if(argI.startsWith(ARGUMENT_PREFIX)){

                //查找参数，下一个命令之前的参数都是当前命令的
                List<String> args = new ArrayList<>(3);
                int argCount = 1;
                while(i + argCount < len && !temp[ i + argCount].startsWith(ARGUMENT_PREFIX)){
                    args.add(temp[ i + argCount]);
                    ++argCount;
                }
                String[] argArray = new String[args.size()];
                args.toArray(argArray);
                map.put(argI ,argArray);

                //跳过以使用的参数
                i+=argCount -1;
            }else{
                throw new InitializationException("argument is null or not in accordance with the rules ,exp: \r\n".concat(startupArgumentHelp()));
            }
        }
        return map;
    }

    public static String startupArgumentHelp(){
        return CommandManager.startupCommand("-help");
    }

    public static int port(){
        if(port == DEFAULT_PORT) {
            //特殊启动命令，端口命令
            if (argumentMap.containsKey(StartupArgument.COMMAND_PORT)) {
                String portStr = CommandManager.startupCommand(StartupArgument.COMMAND_PORT, argumentMap.get(StartupArgument.COMMAND_PORT));
                try {
                    port = Integer.parseInt(portStr);
                } catch (Exception e) {
                    System.err.println("Ports can only be integers ,your port : ".concat(portStr).concat("\r\n").concat(startupArgumentHelp()));
                    System.exit(0);
                }
            }
        }
        return port;
    }
}
